package org.bookie.model.services.impl;

import java.util.List;

import org.bookie.model.Period;
import org.bookie.model.Transaction;
import org.bookie.model.User;
import org.bookie.model.services.TransactionDAO;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class HibernateTransactionDAO extends GenericHibernateDAO<Transaction, Long> implements TransactionDAO {
	
	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<Transaction> findByUser(User user, Period period) {
		Criteria criteria = createCriteria(user, false);
		addPeriodCriteria("date", criteria, period);
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<Transaction> findByUser(User user, boolean asc) {
		return createCriteria(user, asc).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Transaction> findByUserId(Long id, boolean asc){
		Criteria criteria = getSession().createCriteria(getPersistentClass());
		criteria.createCriteria("user").add(Restrictions.eq("id", id));
		addOrderCriteria(criteria, asc);
		return criteria.list();
	}
	
	private Criteria createCriteria(User user, boolean asc){
		Criteria criteria = getSession().createCriteria(getPersistentClass());
		criteria.add(Restrictions.eq("user", user));
		addOrderCriteria(criteria, asc);
		return criteria;
	}
	
	private void addOrderCriteria(Criteria criteria, boolean asc){
		Order order = asc?Order.asc("date"):Order.desc("date");
		criteria.addOrder(order);
	}

}
